<template>
    <div class="array-container">
        <div class="array-header">
            <div class="array-title">{{ this.schema.title }}</div>
            <div class="array-description">{{ this.schema.description }}</div>
        </div>
        <div class="array-body">
            <div class="array-items">
                <!-- 动态键值对列表 -->
                <div v-for="(item, index) in items" :key="item.id" class="array-item">
                    <div class="value-section">
                        <!-- 如果值类型是object或者字典完全复用 VueForm  -->
                        <template v-if="valueSchema.type === 'object'">
                            <div class="value-border">
                                <vue-form :schema="valueSchema" :ui-schema="valueUiSchema" v-model="item.value"
                                    :formProps="formProps" :formFooter="formFooter"></vue-form>
                            </div>
                        </template>
                        <!-- 如果值类型是array -->
                        <template v-if="valueSchema.type === 'array'">
                            <div class="value-border">
                                <DictionaryValueArray :schema="valueSchema" :rootFormData="item.value"
                                    :ui-schema="valueUiSchema">
                                </DictionaryValueArray>
                            </div>
                        </template>
                        <!-- 如果是字符串 -->
                        <template v-else-if="valueSchema.type === 'string'">
                            <el-input class="value-input" size="mini" v-model="item.value" @change="handleValueChange">
                            </el-input>
                        </template>
                        <!-- 如果是数字 -->
                        <template v-else-if="valueSchema.type === 'integer' || valueSchema.type === 'number'">
                            <el-input-number size="mini" class="value-input" v-model="item.value" placeholder="值"
                                @change="handleValueChange">
                            </el-input-number>
                        </template>
                        <!-- 如果是布尔 -->
                        <template v-else-if="valueSchema.type === 'boolean'">
                            <el-switch v-model="item.value" @change="handleValueChange" active-color="#13ce66"
                                inactive-color="#ff4949">
                            </el-switch>
                        </template>

                    </div>
                    <div class="item-actions">
                        <el-button class="delete-button" size="mini" type="danger" icon="el-icon-delete"
                            @click="removeItem(index)" />
                    </div>
                </div>
            </div>

            <div class="add-button">
                <el-button size="mini" type="primary" icon="el-icon-plus" @click="addItem">
                    添加元素
                </el-button>
            </div>
        </div>

    </div>
</template>

<script>
import VueForm from '@lljj/vue-json-schema-form'
import { v4 as uuidv4 } from 'uuid';

export default {
    name: 'DictionaryValueArray',
    components: { VueForm },
    props: {
        schema: {
            type: Object,
            default: () => ({})
        },
        rootFormData: {
            type: Array,
            default: () => ([])
        },
        uiSchema: {
            type: Object,
            default: () => ({})
        },
    },
    watch: {
        items: {
            handler(val) {
                this.updateFormData()
            },
            deep: true
        }
    },
    data() {
        return {
            formProps: {
                layoutColumn: 1, // 1 2 3 ，支持 1 2 3 列布局，如果使用inline表单这里配置无效
                inline: true, // 行内表单模式，建议：开启时labelPosition不要配置top, antd不要配置labelCol wrapperCol
                inlineFooter: false, // 如果想要保存按钮和表单元素一行显示，需要配置 true
                labelSuffix: '：', // label后缀
                labelPosition: 'left', // 表单域标签的位置
                isMiniDes: true, // 是否优先mini形式显示描述信息（label文字和描述信息同行显示）
                defaultSelectFirstOption: true, // 单选框必填，是否默认选中第一个
                popover: {}, // 透传给ui 组件库的popver组件，比如element ui Popover，antd a-popover
                size: 'mini'
            },
            formFooter: {
                show: false, // 是否显示默认底部
                okBtn: '保存', // 确认按钮文字
                cancelBtn: '取消' // 取消按钮文字
            },
            items: this.normalizeInitialData(),
        }
    },
    mounted() {

    },

    computed: {
        valueSchema() {
            return this.schema.items
        },

        // 提取值的ui配置
        valueUiSchema() {
            const patternKeys = Object.keys(this.uiSchema.items?.patternProperties || {})
            return patternKeys.length
                ? this.uiSchema.items.patternProperties[patternKeys[0]]
                : {}
        },

    },
    methods: {
        // 初始化数据处理
        normalizeInitialData() {
            return this.rootFormData.map(item => ({
                id: `new_${uuidv4()}`, // 更唯一的ID
                value: item
            }));
        },

        // 添加新项
        addItem() {
            this.items.push({
                id: `new_${uuidv4()}`,
                value: this.getDefaultValue()
            })
            this.updateFormData();

        },

        // 根据schema类型获取默认值
        getDefaultValue() {
            switch (this.valueSchema.type) {
                case 'object': return {}
                case 'array': return []
                case 'number': return 0
                case 'boolean': return true
                default: return ''
            }
        },

        // 删除项
        removeItem(index) {
            this.items.splice(index, 1)
            this.updateFormData()
        },

        handleValueChange(event) {
            this.updateFormData();
        },

        // 更新表单数据
        updateFormData() {
            // 将数组转换回对象格式
            const newValue = this.items.reduce((acc, { value }) => {
                if (value) acc.push(value);
                return acc;
            }, []);
            // 清空旧数据
            this.rootFormData.length = 0;
            // 添加新数据
            this.rootFormData.push(...newValue);
        },
    },
}
</script>

<style scoped>
.array-container {
    margin-bottom: 50px;

}

.array-title {
    display: block;
    width: 100%;
    line-height: 26px;
    margin-bottom: 8px;
    font-size: 15px;
    font-weight: 700;
    border: 0;
}

.array-description {
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 10px;
    color: #999;
}

.array-items {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.array-item {
    display: flex;
    margin-bottom: 12px;
    margin-right: 20px;
}

.item-actions {
    display: flex;
    align-items: flex-start;
}

.value-section,
.delete-button {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-right: 10px;
}

.value-border {
    border: 1px solid var(--ui-border-color-base);
    border-radius: 4px;
    padding: 12px;
}

.add-button {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.el-input>>>.el-input__prefix {
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 适配不同表单元素的样式 */
.value-section>>>.el-input,
.value-section>>>.el-input-number,
.value-section>>>.el-select {
    width: 160px;
}
</style>